/** @format */

/**
 *  前置检查
 *
 * @export
 * @param {IFunction[]} checks
 * @return {*}
 */
export default function preCheck(checks: IFunction[]) {
  return function (target: Object, name: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value

    descriptor.value = async function (...args: any[]) {
      let [context, otherArgs = {}, services = [], preCheckData = {}] = args
      for (let i = 0; i < checks.length; i++) {
        const checkFn = checks[i]

        let result = await checkFn(context, { ...otherArgs }, services, preCheckData)
        result = result || {}
        // 校验报错
        if ((result as IErrorResult)?.success === false && (result as IErrorResult)?.code) {
          return result
        }

        preCheckData = { ...preCheckData, ...result }
      }
      return method.apply(target, [context, { ...otherArgs }, services, preCheckData])
    }
  }
}
